package com.example.userlogin.service;

import com.example.userlogin.dto.SignupRequest;
import com.example.userlogin.entity.User;
import com.example.userlogin.exception.UserRegistrationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户注册服务
 * 职责：处理用户注册流程、注册后的业务逻辑
 */
@Service
public class UserRegistrationService {

    private static final Logger logger = LoggerFactory.getLogger(UserRegistrationService.class);

    @Autowired
    private UserService userService;

    @Autowired
    private UserAuditService userAuditService;

    @Autowired
    private NotificationService notificationService;

    /**
     * 用户注册主流程
     */
    @Transactional(rollbackFor = Exception.class)
    public User registerUser(SignupRequest signupRequest) {
        try {
            logger.info("开始注册用户: {}", signupRequest.getUsername());

            // 1. 创建用户
            User user = userService.createUser(signupRequest);
            logger.info("用户创建成功: {}", user.getUsername());

            // 2. 记录注册审计日志
            userAuditService.logUserRegistration(user);

            // 3. 发送欢迎通知（异步）
            notificationService.sendWelcomeNotification(user);

            logger.info("用户注册完成: {}", user.getUsername());
            return user;

        } catch (Exception e) {
            logger.error("用户注册失败: {}, 错误: {}", signupRequest.getUsername(), e.getMessage());
            throw new UserRegistrationException("用户注册失败: " + e.getMessage(), e);
        }
    }

    /**
     * 验证注册请求
     */
    public void validateRegistrationRequest(SignupRequest signupRequest) {
        if (signupRequest == null) {
            throw new IllegalArgumentException("注册请求不能为空");
        }

        if (signupRequest.getUsername() == null || signupRequest.getUsername().trim().isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }

        if (signupRequest.getEmail() == null || signupRequest.getEmail().trim().isEmpty()) {
            throw new IllegalArgumentException("邮箱不能为空");
        }

        if (signupRequest.getPassword() == null || signupRequest.getPassword().length() < 6) {
            throw new IllegalArgumentException("密码长度不能少于6位");
        }

        // 可以添加更多验证规则
        validateUsernameFormat(signupRequest.getUsername());
        validateEmailFormat(signupRequest.getEmail());
        validatePasswordStrength(signupRequest.getPassword());
    }

    /**
     * 验证用户名格式
     */
    private void validateUsernameFormat(String username) {
        if (!username.matches("^[a-zA-Z0-9_]{3,20}$")) {
            throw new IllegalArgumentException("用户名只能包含字母、数字和下划线，长度3-20位");
        }
    }

    /**
     * 验证邮箱格式
     */
    private void validateEmailFormat(String email) {
        if (!email.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$")) {
            throw new IllegalArgumentException("邮箱格式不正确");
        }
    }

    /**
     * 验证密码强度
     */
    private void validatePasswordStrength(String password) {
        // 简单的密码强度验证
        if (password.length() < 8) {
            throw new IllegalArgumentException("密码长度至少8位");
        }
        
        boolean hasLetter = password.matches(".*[a-zA-Z].*");
        boolean hasDigit = password.matches(".*\\d.*");
        
        if (!hasLetter || !hasDigit) {
            throw new IllegalArgumentException("密码必须包含字母和数字");
        }
    }
}